<?php

namespace yunj\app\admin\controller\member;

use yunj\app\admin\model\AdminMember;
use yunj\app\admin\controller\Controller;
use yunj\app\admin\validate\member\LoginValidate as Validate;

class MemberLoginController extends Controller implements MemberLoginControllerInterface {

    /**
     * token盐值
     * @var string
     */
    const TOKEN_SALT = '456c2e75fe0faa57fd1cfd87117e0963';

    /**
     * @return Validate
     */
    public static function getValidate(): Validate {
        /** @var Validate $validate */
        $validate = app(Validate::class);
        return $validate;
    }

    /**
     * 登录
     * @return \think\response\View|\yunj\core\response\Json
     */
    public function login() {
        if (request()->isPost()) {
            return $this->loginHandle();
        }
        $vars = [
            'captchaUrl' => build_url('yunjAdminCaptcha'),
            'requestUrl' => build_url('yunjAdminMemberLogin'),
        ];
        return $this->view('member/login', $vars);
    }

    /**
     * 登录处理
     * @return \yunj\core\response\Json
     */
    protected function loginHandle() {
        $param = request()->all();
        $validate = self::getValidate();
        $res = $validate->scene('Login')->check($param);
        if (!$res) return error_json($validate->getError());
        $param = $validate->getData();
        $member = $param['member'];
        $data = admin_member_login_service()->login($member);
        cookie('admin_token', $data['token']);  // 验证成功会自动延长有效期，此处可不设置有效时间
        return success_json(['url' => YUNJ_ADMIN_URL]);
    }

    /**
     * 退出/切换账户
     * @return \think\response\Redirect
     */
    public function logout() {
        admin_member_login_service()->logout();
        return redirect(build_url('yunjAdminMemberLogin'));
    }

    /**
     * 生成token
     * @param AdminMember $member
     * @return string
     */
    public function generateToken(AdminMember $member): string {
        if (!$member) return '';
        // 增加user-agent防止token被盗用
        $userAgent = request()->header('user-agent');
        return md5($member->id . $member->username . $userAgent . self::TOKEN_SALT);
    }

    /**
     * 获取当前token
     * @return string
     */
    public function getRequestToken(): string {
        $token = cookie('admin_token');
        return $token ? (string)$token : '';
    }


}